﻿// <com.woyouqiu.Copyright>
// --------------------------------------------------------------
// <copyright>上海有求网络科技有限公司 2015</copyright>
// <Solution>Vecen.BangChuang</Solution>
// <Project>Vecen.BangChuang.Core</Project>
// <FileName>OrderDomainService.cs</FileName>
// <CreateTime>2017-05-23 22:40</CreateTime>
// <Author>何苗</Author>
// <Email>hemiao@woyouqiu.com</Email>
// <log date="2017-05-23 22:40" version="00001">创建</log>
// --------------------------------------------------------------
// </com.woyouqiu.Copyright>

using System.Linq;
using System.Threading.Tasks;
using Abp.Domain.Repositories;
using Abp.UI;
using Vecen.BangChuang.BangChuang.Mall;

namespace Vecen.BangChuang.BangChuang.DomainServices.Mall {
    public class OrderDomainService: BangChuangDomainServiceBase {
        private readonly IRepository<Order> _orderRepository;
        private readonly IRepository<OrderItem> _orderItemRepository;
        private readonly IRepository<OrderPriceChange> _orderPriceChangeRepository;

        public OrderDomainService(IRepository<Order> orderRepository,
            IRepository<OrderItem> orderItemRepository,
            IRepository<OrderPriceChange> orderPriceChangeRepository) {
            _orderRepository = orderRepository;
            _orderItemRepository = orderItemRepository;
            _orderPriceChangeRepository = orderPriceChangeRepository;
        }

        /// <summary>
        /// 检查是否有有效订单的商品
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public Task<bool> IsHasEffectiveOrderWithProductIdAsync(int productId) {
            var query = _orderRepository.GetAllIncluding(c => c.OrderItems)
                .Where(c => c.IsBlankOut == false)
                .Where(c => c.OrderItems.Any(item => item.ProductId == productId));
            return Task.Run(() => query.Any());
        }


        /// <summary>
        /// 根据商品ID,删除无效订单
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public async Task DeleteOrderWithProductIdAsync(int productId) {
            var query = _orderRepository.GetAllIncluding(c => c.OrderItems)
                .Where(c => c.OrderItems.Any(item => item.ProductId == productId));
            var hasEffectiveOrder = await Task.Run(() => query.Any(c => c.IsBlankOut == false));
            if(hasEffectiveOrder) {
                throw new UserFriendlyException("删除订单失败!", "指定商品存在有效的订单!");
            }

            var orders = await Task.Run(() => query.ToList());
            foreach(var order in orders) {
                await _orderPriceChangeRepository.DeleteAsync(c => c.OrderId == order.Id);
                await _orderItemRepository.DeleteAsync(c => c.OrderId == order.Id);
                await _orderRepository.DeleteAsync(order);
            }
        }
    }
}